$(function(){
    var body = $('body');

    //cập nhật chỉnh sửa câu hỏi
    body.on('click', '.save-question', function() {
        var widget_edit = $(this).parent().parent();
        var widget_box = $(this).parent().parent().parent();
        var type = widget_box.attr('builder');

        switch (type){
            case "1":{
                var title = widget_edit.find('.widget-edit-question').find('textarea').val();
                if(title == ""){
                    widget_edit.find('.widget-edit-question').find('textarea').effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
                    widget_edit.find('.widget-edit-question').find('textarea').focus();
                }else{
                    var number = widget_edit.find('.widget-edit-answer').find('ul').find('li').size();
                    widget_box.find('.widget-question').find('.widget-main').find('ul').html("");
                    var flat = true;
                    for(var i=0; i<number; i++){
                        var name = $(widget_edit.find('.widget-edit-answer').find('ul').find('li').get(i)).find('.input');
                        if(name.val() == ""){
                            name.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
                            name.focus();
                            flat = false;
                            break;
                        }else{
                            widget_box.find('.widget-question').find('.widget-main').find('ul').append('<li>'+name.val()+'</li>');
                        }
                    }
                    if(flat && i == number){
                        widget_box.find('.widget-question').find('.widget-header').find('.col-title').text(title);

                        widget_box.removeClass('widget-editing');
                        widget_box.find('.widget-question').show();
                        widget_edit.hide();
                    }
                }
                break;
            }
            case "2":{
                title = widget_edit.find('.widget-edit-question').find('textarea').val();
                if(title == ""){
                    widget_edit.find('.widget-edit-question').find('textarea').effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
                    widget_edit.find('.widget-edit-question').find('textarea').focus();
                }else{
                    number = widget_edit.find('.widget-edit-answer').find('ul').find('li').size();
                    widget_box.find('.widget-question').find('.widget-main').find('ul').html("");
                    flat = true;
                    for(i=0; i<number; i++){
                        name = $(widget_edit.find('.widget-edit-answer').find('ul').find('li').get(i)).find('.input');
                        if(name.val() == ""){
                            name.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
                            name.focus();
                            flat = false;
                            break;
                        }else{
                            widget_box.find('.widget-question').find('.widget-main').find('ul').append('<li><input type="checkbox"> <label>'+name.val()+'</label></li>');
                        }
                    }
                    if(flat && i == number){
                        widget_box.find('.widget-question').find('.widget-header').find('.col-title').text(title);

                        widget_box.removeClass('widget-editing');
                        widget_box.find('.widget-question').show();
                        widget_edit.hide();
                    }
                }
                break;
            }
            case "3":{
                title = widget_edit.find('.widget-edit-question').find('textarea').val();
                if(title == ""){
                    widget_edit.find('.widget-edit-question').find('textarea').effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
                    widget_edit.find('.widget-edit-question').find('textarea').focus();
                }else{
                    var row = widget_edit.find('.col-edit-row').find('ul').find('li').size();
                    var column = widget_edit.find('.col-edit-column').find('ul').find('li').size();

                    //Kiểm tra nhập liệu
                    flat = true;
                    for(var j=0; j<row; j++){
                        var rowInput = $(widget_edit.find('.col-edit-row').find('ul').find('li').get(j)).find('.input');
                        if(rowInput.val() == ""){
                            rowInput.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
                            rowInput.focus();
                            flat = false;
                            break;
                        }
                    }

                    if(j == row){
                        for(i=0; i<column; i++){
                            var columnInput = $(widget_edit.find('.col-edit-column').find('ul').find('li').get(i)).find('.input');
                            if(columnInput.val() == ""){
                                columnInput.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
                                columnInput.focus();
                                flat = false;
                                break;
                            }
                        }
                    }

                    //Kiểm tra
                    if(flat && i == column && j == row){
                        widget_box.find('.widget-question').find('.widget-header').find('.col-title').text(title);
                        widget_box.find('.widget-question').find('.widget-main').find('.table').html("");
                        var html = '<thead>';
                        html += '<tr>';
                        html += '<th></th>';
                        for(i=0; i<column; i++){
                            var columnName = $(widget_edit.find('.col-edit-column').find('ul').find('li').get(i)).find('.input').val();
                            html +=('<th>'+columnName+'</th>');
                        }
                        html += '</tr>';
                        html += '</thead>';
                        html += '<tbody>';

                        for(j=0; j<row; j++){
                            var rowName = $(widget_edit.find('.col-edit-row').find('ul').find('li').get(j)).find('.input').val();
                            html += '<tr>';
                            for(i=0; i<=column; i++){
                                if(i == 0){
                                    html += '<td>'+rowName+'</td>';
                                }else{
                                    html += '<td><input name="answer-4" type="radio"></td>';
                                }
                            }
                            html += '</tr>';
                        }
                        html += '</tbody>';
                        widget_box.find('.widget-question').find('.widget-main').find('.table').append(html);

                        widget_box.removeClass('widget-editing');
                        widget_box.find('.widget-question').show();
                        widget_edit.hide();
                    }
                }
                break;
            }
            default :{

                break;
            }
        }

    });

    //Hủy lưu chỉnh sửa câu hỏi
    body.on('click', '.cancel-question', function() {
        var widget_box = $(this).parent().parent().parent();
        var title = widget_box.find('.widget-edit').find('.col-title').val();
        if(title == ""){
            widget_box.remove();
        }else{
            widget_box.removeClass('widget-editing');
            widget_box.find('.widget-question').show();
            widget_box.find('.widget-edit').hide();
        }
    });

    //Thêm câu trả lời
    body.on('click', '.widget-edit-add-question', function() {
        var html = '<li class="form-group">';
        html += '<div class="col-answer">';
        html += '<div class="col-left">';
        html += '<input class="input" type="text" placeholder="Answer">';
        html += '</div>';
        html += '<div class="col-right">';
        html += '<span class="widget-edit-add-question"><i class="fa fa-plus-circle"></i></span>';
        html += '<span class="widget-edit-remove-question"><i class="fa fa-times-circle"></i></span>';
        html += '</div>';
        html += '</li>';

        $(this).parent().parent().parent().after(html);

    });

    //Xóa Câu trả lời
    body.on('click', '.widget-edit-remove-question', function() {
        var number = $(this).parent().parent().parent().parent().find('.form-group').size();
        if(number > 1){
            $(this).parent().parent().parent().remove();
        }
    });

    $(".widget-tooltip").on("mouseover", function () {
        console.log("a");
    });


    //Chọn radio in table
    body.on('mousedown', '.table tr td', function() {

        if($(this).find('input').is( ":checked")){
            $(this).find('input').prop('checked', false);
        }else{
            $(this).find('input').prop('checked', true);
        }
    });

    //open menu
    body.on('click', '.dropdown-toggle', function() {
        if($(this).parent().hasClass('open')){
            $(this).parent().removeClass('open');
            $(this).parent().find('.sub-menu').animate({
                height: "toggle"
            }, 300);
        }else{
            $(this).parent().parent().find('.open').find('.sub-menu').animate({
                height: "toggle"
            }, 300);
            $(this).parent().parent().find('.nav-item').removeClass('open');

            $(this).parent().addClass('open');

            $(this).parent().find('.sub-menu').animate({
                height: "toggle"
            }, 300);
        }
    });

    body.on('click', '.survey-builder-close', function(){
        var button = $('#survey-builder-button');
        var builder = $('.survey-page-builder');
        var page = $('.survey-page-content');
        button.show();
        builder.hide();
        page.css('width','99%').css('margin-left','1%');

    });

    /***
     * Create new campaign
     */
    $('.tab-campaign-management').click(function(){
        var tab_campaign = $('#tab-campaign');
        var tab_buzzer = $('#tab-buzzer');
        var tab = $(this).attr('tab-data');
        if(tab == "buzzer"){
            $('.tab-buzzer').addClass('active');
            tab_buzzer.show();
            $('.tab-campaign').removeClass('active');
            tab_campaign.hide();
            //Get buzzier
            var criteria_male = $('#criteria_male').prop("checked");
            var criteria_female = $('#criteria_female').prop("checked");
            var criteria_14_19 = $('#criteria_14_19').prop("checked");
            var criteria_20_29 = $('#criteria_20_29').prop("checked");
            var criteria_30_39 = $('#criteria_30_39').prop("checked");
            var criteria_40_49 = $('#criteria_40_49').prop("checked");
            var criteria_50 = $('#criteria_50').prop("checked");
            var criteria_province = $('#criteria_province').prop("checked");
            var criteria_hcm = $('#criteria_hcm').prop("checked");
            var criteria_hanoi = $('#criteria_hanoi').prop("checked");
            var criteria_single = $('#criteria_single').prop("checked");
            var criteria_married = $('#criteria_married').prop("checked");
            var criteria_1_child = $('#criteria_1_child').prop("checked");
            var criteria_2_child = $('#criteria_2_child').prop("checked");
            $.ajax({
                type:"POST",
                url:"management/getBuzzer",
                dataType:"json",
                data:{'criteria_male': criteria_male, 'criteria_female': criteria_female, 'criteria_14_19': criteria_14_19,
                    'criteria_20_29': criteria_20_29, 'criteria_30_39': criteria_30_39, 'criteria_40_49': criteria_40_49,
                    'criteria_50': criteria_50, 'criteria_province': criteria_province, 'criteria_hcm': criteria_hcm, 'criteria_hanoi': criteria_hanoi,
                    'criteria_single': criteria_single, 'criteria_married': criteria_married, 'criteria_1_child': criteria_1_child,
                    'criteria_2_child': criteria_2_child
                },
                success:(function(data){
                    if(data.status == "ok"){
                        var tab_buzzer = $('#tab-buzzer');
                        tab_buzzer.find('.number-buzzer-invited').text("Have "+data.data.length+" buzzer");
                        tab_buzzer.find('table tbody').html("");
                        for(var i =0; i < data.data.length; i++){
                            var html = "";
                            html += "<tr>";
                            html += "<td>"+data.data[i].username+"</td>";
                            html += "<td>"+data.data[i].buzzscore+"</td>";
                            html += "<td><input type='checkbox' checked></td>";
                            html += "</tr>";
                            tab_buzzer.find('table tbody').append(html);
                        }

                    }
                })
            });
        }else{
            tab_buzzer.hide();
            $('.tab-buzzer').removeClass('active');
            tab_campaign.addClass('active').show();
            $('.tab-campaign').addClass('active');
        }
    });

    $('#save_campaign').click(function(){
        var campaign_type = $('#campaign_type_live').prop("checked");
        var campaign_name = $('#campaign_name');
        var campaign_short_des = $('#short_description');
        var campaign_long_des = $('#long_description');
        var campaign_begin = $('#begin').val();
        var campaign_end = $('#end').val();
        var campaign_img = Array();
        var criteria_male = $('#criteria_male').prop("checked");
        var criteria_female = $('#criteria_female').prop("checked");
        var criteria_14_19 = $('#criteria_14_19').prop("checked");
        var criteria_20_29 = $('#criteria_20_29').prop("checked");
        var criteria_30_39 = $('#criteria_30_39').prop("checked");
        var criteria_40_49 = $('#criteria_40_49').prop("checked");
        var criteria_50 = $('#criteria_50').prop("checked");
        var criteria_province = $('#criteria_province').prop("checked");
        var criteria_hcm = $('#criteria_hcm').prop("checked");
        var criteria_hanoi = $('#criteria_hanoi').prop("checked");
        var criteria_single = $('#criteria_single').prop("checked");
        var criteria_married = $('#criteria_married').prop("checked");
        var criteria_1_child = $('#criteria_1_child').prop("checked");
        var criteria_2_child = $('#criteria_2_child').prop("checked");

        //var campaign_img_size = $('.campaign_img').size();
        $('.campaign_img').each(function(){
            campaign_img.push($(this).val());
        });

        if(campaign_name.val() == ""){
            campaign_name.focus();
            campaign_name.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
            campaign_name.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
        }else if(campaign_short_des.val() == "") {
            campaign_short_des.focus();
            campaign_short_des.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
            campaign_short_des.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
        }else if(campaign_long_des.val() == ""){
            campaign_long_des.focus();
            campaign_long_des.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
            campaign_long_des.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
        }else{
            $.ajax({
                type:"POST",
                url:"management/saveCampaign",
                dataType:"json",
                data:{'type': campaign_type, 'name': campaign_name.val(), 'short_des': campaign_short_des.val(), 'long_des': campaign_long_des.val(),
                    'begin': campaign_begin, 'end': campaign_end, 'image': campaign_img, 'criteria_male': criteria_male, 'criteria_female': criteria_female,
                    'criteria_14_19': criteria_14_19, 'criteria_20_29': criteria_20_29, 'criteria_30_39': criteria_30_39, 'criteria_40_49': criteria_40_49,
                    'criteria_50': criteria_50, 'criteria_province': criteria_province, 'criteria_hcm': criteria_hcm, 'criteria_hanoi': criteria_hanoi,
                    'criteria_single': criteria_single, 'criteria_married': criteria_married, 'criteria_1_child': criteria_1_child, 'criteria_2_child': criteria_2_child
                },
                success:(function(data){
                    if(data.status == "ok"){

                    }
                })
            });
        }

    });

    body.on('click', '.remove-upload-m', function(){
        var mid = $(this).attr("mid");
        var index = $(this).parent().index();
        $.ajax({
            type:"POST",
            url:"management/removeImages",
            dataType:"json",
            data:{'mid': mid},
            success:(function(data){
                if(data.status == "ok"){
                    var tab_campaign_upload = $('#tab-campaign-upload');
                    $(tab_campaign_upload.find('li').get(index)).remove();
                }
            })
        });

    });

    //Criteria
    //gender criteria
    body.on('click', '.col-criteria-radio', function(){
        $(this).parent().find('.col-criteria-radio').removeClass('selected');
        $(this).addClass('selected');
        var gender = $(this).find('input').val();
        var result = $('.col-criteria-result');
        $('#total_criteria').find('.gender').val(gender);
        switch (gender){
            case "0":{
                result.find('.result-show').find('.gender ul li').text("Tất cả");
                break;
            }
            case "1":{
                result.find('.result-show').find('.gender ul li').text("Nam");
                break;
            }
            case "2":{
                result.find('.result-show').find('.gender ul li').text("Nữ");
                break;
            }
            default :{
                result.find('.result-show').find('.gender ul li').text("Tất cả");
                break;
            }
        }
        //loading buzzer
        getBuzzer();
    });

    //age criteria
    body.on('click', '.col-select-age .criteria-popup li', function(){
        var value = $(this).attr('value');
        $(this).parent().find('li').each(function(){
            $(this).removeClass('selected');
        });
        $(this).addClass('selected');
        //set age
        $(this).parent().parent().parent().find('.criteria-select').find('.text').text(value);
        //hide popup
        $(this).parent().parent().toggle();
        //set value age criteria
        var type = $(this).parent().parent().attr("type");
        var result = $('.col-criteria-result');
        if(type == "begin"){
            result.find('.begin_age').val(value);
        }else{
            result.find('.end_age').val(value);
        }
        //set show result
        var select_age = $('.col-select-age');
        var begin = select_age.find('.begin-age').find('.selected').attr('value');
        var end = select_age.find('.end-age').find('.selected').attr('value');
        if(begin > end){
            if(type == "begin"){
                $(select_age.find('.end-age')).parent().find('.criteria-select').find('.text').text(begin);
                select_age.find('.end-age').find('li').each(function(){
                    var value = $(this).attr("value");
                    if(value == begin){
                        $(this).addClass('selected');
                    }else{
                        $(this).removeClass('selected');
                    }
                });
            }else{
                $(select_age.find('.begin-age')).parent().find('.criteria-select').find('.text').text(end);
                select_age.find('.begin-age').find('li').each(function(){
                    var value = $(this).attr("value");
                    if(value == end){
                        $(this).addClass('selected');
                    }else{
                        $(this).removeClass('selected');
                    }
                });
            }
        }

        result.find('.result-show').find('.age ul li').text(begin + " - " + end);
        //loading buzzer
        getBuzzer();
    });

    //location criteria
    body.on('click', '.criteria-location .list li', function(){
        var result = $('.criteria-location');
        if($(this).hasClass('selected')){
            //remove province
            $(this).removeClass('selected');
            //all click
            if($(this).hasClass('all')){
                $(this).parent().find('li').each(function(){
                    $(this).removeClass('selected');
                });
                result.find('.result ul').find('li').each(function(){
                    $(this).remove();
                });

                result.find('.result ul').find('.location-0').remove();
            }else{
                var value = $(this).attr('value');

                result.find('.result ul').find('.location-'+value).remove();


            }
        }else{
            //add province
            $(this).addClass('selected');
            //all click
            if($(this).hasClass('all')){
                $(this).parent().find('li').each(function(){
                    $(this).addClass('selected');
                });
                result.find('.result ul').find('li').each(function(){
                    $(this).remove();
                });
                var html = '';
                html += '<li class="location-0">';
                html += '<span class="text">Tất cả</span>';
                html += '<span class="icon"><i class="fa fa-times"></i></span>';
                html += '</li>';
                result.find('.result ul').append(html);
            }else{
                value = $(this).attr('value');
                var text = $(this).text();
                result.find('.result ul').find('.location-0').remove();
                html = '';
                html += '<li class="location-'+value+'">';
                html += '<span class="text">'+ text +'</span>';
                html += '<span class="icon"><i class="fa fa-times"></i></span>';
                html += '</li>';
                result.find('.result ul').append(html);
                //add show
                var criteria_result = $('.col-criteria-result');
                criteria_result.find('.result-show').find('.location').find('ul').append('<li>'+text+'</li>');
                criteria_result.find('#total_criteria').append('<input class="location" type="hidden" name="location[]" value="'+value+'">');
            }
        }
        //loading buzzer
        getBuzzer();
    });

    //Sự kiện select 1 category criteria
    body.on('click', '.criteria-select', function(){
        $(this).parent().find('.criteria-popup').toggle();
    });

    //Sự kiện lấy ra filter của 1 category criteria
    body.on('click', '.criteria-popup li', function(){
        $(this).parent().parent().toggle();
        var atid = $(this).attr('atid');
        if(!$(this).hasClass('selected')){
            $.ajax({
                type:"POST",
                url:"management/getCriteria",
                data:{'atid': atid},
                success:(function(data){
                    $('#criteria_'+atid).addClass("selected");
                    $('#campaign-criteria').append(data);
                })
            });
        }
    });

    body.on('click', '.col-search-criteria-header', function(){
        $(this).parent().find('.col-search-criteria-body').toggle();
    });

    body.on('click', '.col-search-criteria-parent .icon', function(){
        var atid = $(this).parent().parent().attr("id").replace("criteria_item_", "");
        var criteria_item = $('#criteria_item_'+atid);
        var size_child = criteria_item.find('.col-search-criteria-child').find('li').size();
        if(size_child > 0){
            //Nếu children đã được thêm vào thì mở children ra hoặc đóng lại nếu đã mở
            criteria_item.find('.col-search-criteria-child').toggle();
        }else{
            //Nếu children chưa được thêm vào thì lấy dữ liệu rồi thêm vào
            $.ajax({
                type:"POST",
                url:"management/getCriteriaChildren",
                dataType: "json",
                data:{'atid': atid},
                success:(function(data){
                    if(data.status == "ok"){
                        var html = '';
                        var criteria_item = $('#criteria_item_'+atid);
                        criteria_item.find('.col-search-criteria-child').html("");
                        for(var i = 0; i < data.data.length; i++){
                            if(data.data[i].children){
                                html = '<li class="parent" id="criteria_item_'+data.data[i].atid+'" title="'+data.data[i].parent_title+'" tag="'+data.data[i].attr_tag+'">';
                            }else{
                                html = '<li class="children" id="criteria_item_'+data.data[i].atid+'" title="'+data.data[i].parent_title+'" tag="'+data.data[i].attr_tag+'">';
                            }
                            html += '<div class="col-search-criteria-parent">';
                            if(data.data[i].children){
                                html += '<span class="icon"><i class="fa fa-caret-right"></i></span>';
                            }
                            html += '<span class="text">'+data.data[i].attr_name+'</span>';
                            html += '</div>';
                            if(data.data[i].children){
                                html += '<ul class="col-search-criteria-child">';
                                html += '</ul>';
                            }
                            html += '</li>';
                            criteria_item.find('.col-search-criteria-child:eq(0)').append(html);
                        }
                    }
                })
            });
        }
    });

    //Thay đổi buzzer
    body.on('click', '.col-search-criteria-parent .text', function(){

        //Kiểm tra object có tag không, có thì add tag, không có thì mở sub criteria
        if($(this).parent().parent().hasClass('selected')){
            //Remove add criteria

        }else{
            var tag = $(this).parent().parent().attr('tag');
            if(tag == "1"){

                var atid = $(this).parent().parent().attr("id").replace("criteria_item_", "");
                var parent_title = $(this).parent().parent().attr('title');
                var children_title = $(this).text();
                var html = '';
                if(parent_title){
                    var parent_id = $(this).parent().parent().parent().parent().attr('id').replace("criteria_item_", "");
                    window.parentExist = false;
                    //Kiểm tra parent đã được thêm vào chưa
                    $(this).closest('.col-search-criteria').find('.col-search-criteria-selected').find('ul').find('li').each(function(){
                        var parent = $(this).attr("parent");
                        if(parent == parent_id){
                            window.parentExist = true;
                            var content = '';
                            content += '<p class="children">';
                                content += '<span class="text">'+children_title+'</span>';
                                content += '<span class="icon"><i class="fa fa-times"></i></span>';
                            content += '</p>';
                            $(this).append(content);
                        }
                    });
                    if(!window.parentExist){
                        //Chưa tồn tại
                        html += '<li parent="'+parent_id+'">';
                            html += '<p class="parent">';
                                html += '<span class="text">'+parent_title+'</span>';
                                html += '<span class="icon"><i class="fa fa-times"></i></span>';
                            html += '</p>';
                            html += '<p class="children">';
                                html += '<span class="text">'+children_title+'</span>';
                                html += '<span class="icon"><i class="fa fa-times"></i></span>';
                            html += '</p>';
                        html += '</li>';
                    }

                }else{
                    html += '<li>';
                        html += '<p class="children">';
                            html += '<span class="text">'+children_title+'</span>';
                            html += '<span class="icon"><i class="fa fa-times"></i></span>';
                        html += '</p>';
                    html += '</li>';
                }

                $(this).closest('.col-search-criteria').find('.col-search-criteria-selected').find('ul').append(html);
                $(this).parent().parent().addClass('selected');

                //show result
                var result = $('.col-criteria-result');
                var cid = $(this).closest('.criteria-col-item').attr('cid');
                result.find('#total_criteria').append('<input class="criteria" cid="'+cid+'" type="hidden" name="criteria[]" value="'+atid+'">');
                //Kiểm tra xem thuộc lọi criteria nào
                getBuzzer();
            }else{
                //Show children


            }
        }
    });


    //location
    body.on('click', '.criteria-location .search input', function(){
        $(this).parent().parent().find('.list').toggle();
    });



});

var loader = $('#loader');
function hashchanged(){
    var hash = window.location.hash;
    loader.css('display','block');
    switch (hash){
        case "#ccreate":{
            loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
            $.ajax({
                type:"POST",
                url:Root_url+"management/getCreateCampaign",
                data:{},
                success:(function(data){
                    $('.main-tab').html(data);
                    loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                    loader.css('display','none');
                })
            });
            break;
        }
        case  "#campaign":{
            loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
            $('.daterangepicker ').remove();
            $.ajax({
                type:"POST",
                url:Root_url+"management/getCampaign",
                data:{},
                success:(function(data){
                    $('.main-tab').html(data);
                    loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                    loader.css('display','none');
                })
            });
            break;
        }
        case  "#screate":{
            loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
            $('.daterangepicker ').remove();
            $.ajax({
                type:"POST",
                url:Root_url+"management/getCreateSurvey",
                data:{},
                success:(function(data){
                    $('.main-tab').html(data);
                    $.ajax({
                        type: "POST",
                        url:Root_url+"management/getSurveyBuilder",
                        data: {},
                        success: (function (data) {
                            var builder = $('.survey-page-builder');
                            builder.html(data);
                            builder.hide();
                        })
                    });
                    loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                    loader.css('display','none');
                })
            });
            break;
        }
        case  "#survey":{
            loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
            $('.daterangepicker ').remove();
            $.ajax({
                type:"POST",
                url:Root_url+"management/getSurvey",
                data:{},
                success:(function(data){
                    $('.main-tab').html(data);
                    loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                    loader.css('display','none');
                })
            });
            break;
        }
        case "#attributes":{
            loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
            $('.daterangepicker ').remove();
            $.ajax({
                type:"POST",
                url:Root_url+"management/getAttributes",
                data:{},
                success:(function(data){
                    $('.main-tab').html(data);
                    loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                    loader.css('display','none');
                })
            });
            break;
        }
        case "#groups":{

            loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
            $('.daterangepicker ').remove();
            $.ajax({
                type:"POST",
                url:Root_url+"management/getGroup",
                data:{},
                success:(function(data){
                    $('.main-tab').html(data);
                    loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                    loader.css('display','none');
                })
            });
            break;
        }
        default :{
            //Survey edit
            var regSurveyEdit = /(#survey\/)+([0-9]+$)/gi;
            //Survey position
            var regSurveyPosition = /(#position\/)+([0-9]+$)/gi;
            //Survey analytics
            var regSurveyAnalytics = /(#analytics\/)+([0-9]+$)/gi;
            if(regSurveyEdit.test(hash)){
                var reg_number = /[0-9]+$/g;
                var sid = hash.match(reg_number);
                loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
                $('.daterangepicker ').remove();
                $.ajax({
                    type:"POST",
                    url:Root_url+"management/getEditSurvey",
                    data:{'sid': sid[0]},
                    success:(function(data){
                        $('.main-tab').html(data);
                        setTimeout(function(){
                            $.ajax({
                                type: "POST",
                                url:Root_url+"management/getSurveyBuilder",
                                data: {},
                                success: (function (data) {
                                    var builder = $('.survey-page-builder');
                                    builder.html(data);
                                    builder.hide();
                                })
                            });
                            loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                            loader.css('display','none');
                        }, 500);
                    })
                });
            }else if(regSurveyAnalytics.test(hash)){
                reg_number = /[0-9]+$/g;
                sid = hash.match(reg_number);
                loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
                $('.daterangepicker ').remove();
                $.ajax({
                    type:"POST",
                    url:Root_url+"management/getSurveyAnalytics",
                    data:{'sid': sid[0]},
                    success:(function(data){
                        $('.main-tab').html(data);
                        loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                        loader.css('display','none');
                    })
                });

            }else if(regSurveyPosition.test(hash)){
                reg_number = /[0-9]+$/g;
                sid = hash.match(reg_number);
                loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
                $('.daterangepicker ').remove();
                $.ajax({
                    type:"POST",
                    url:Root_url+"management/getSurveyPosition",
                    data:{'sid': sid[0]},
                    success:(function(data){
                        $('.main-tab').html(data);
                        loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                        loader.css('display','none');
                    })
                });
            }else{
                loader.find('.loader-icon').addClass('spinning-cog').removeClass('shrinking-cog');
                $('.daterangepicker ').remove();
                $.ajax({
                    type:"POST",
                    url:Root_url+"management/getCampaign",
                    data:{},
                    success:(function(data){
                        $('.main-tab').html(data);
                        loader.find('.loader-icon').removeClass('spinning-cog').addClass('shrinking-cog');
                        loader.css('display','none');
                    })
                });
            }
            break;
        }
    }
}

//Survey
function surveyBuilder(){
    var button = $('#survey-builder-button');
    var builder = $('.survey-page-builder');
    var page = $('.survey-page-content');
    builder.show();
    button.hide();
    page.css('width','75%').css('margin-left','25%');
}

function saveSurvey(obj){
    var survey_child_title = $('#survey_title');
    if(survey_child_title.val() == ""){
        $('body').scrollTop(0);
        survey_child_title.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
        survey_child_title.find('textarea').focus();
    }else{
        var sid = $('#survey_folder').val();
        $.ajax({
            type:"POST",
            url:Root_url+"management/saveSurveyChild",
            dataType: "json",
            data:{'survey_child_title': survey_child_title.val(), 'sid': sid},
            success:(function(data){
                if(data.status == "ok"){
                    var scid = data.scid;
                    var widget_box = $('.widget-box');
                    var size = widget_box.size();
                    //Từng câu hỏi
                    for(var i = 0; i< size; i++){
                        var widget = $(widget_box.get(i));
                        var question_title = widget.find('.widget-header').find('.col-title').text();
                        var question_type = widget.attr('builder');
                        var question_size = 0;
                        switch(question_type){
                            case "1":{
                                question_size = widget.find('.widget-edit').find('.widget-edit-answer ul li').size();
                                var arrAnswer = Array();
                                for(var j = 0; j < question_size; j++){
                                    var answer_text = $(widget.find('.widget-edit').find('.widget-edit-answer ul li').get(j)).find('input').val();
                                    arrAnswer.push(answer_text);
                                }
                                $.ajax({
                                    type:"POST",
                                    url:Root_url+"management/saveQuestionSingle",
                                    dataType: "json",
                                    data:{'scid': scid, 'question_title': question_title, 'question_type': 1, 'answer': arrAnswer, 'position': i},
                                    success:(function(data){

                                    })
                                });
                                break;
                            }
                            case  "2":{
                                question_size = widget.find('.widget-edit').find('.widget-edit-answer ul li').size();
                                arrAnswer = Array();
                                for(var j = 0; j < question_size; j++){
                                    answer_text = $(widget.find('.widget-edit').find('.widget-edit-answer ul li').get(j)).find('input').val();
                                    arrAnswer.push(answer_text);
                                }
                                $.ajax({
                                    type:"POST",
                                    url:Root_url+"management/saveQuestionMultiple",
                                    dataType: "json",
                                    data:{'scid': scid, 'question_title': question_title, 'question_type': 2, 'answer': arrAnswer, 'position': i},
                                    success:(function(data){

                                    })
                                });
                                break;
                            }
                            case "3":{
                                var row_size = widget.find('.widget-edit').find('.col-edit-row ul li').size();
                                var column_size = widget.find('.widget-edit').find('.col-edit-column ul li').size();
                                var arrAnswerRow = Array();
                                for(var m = 0; m < row_size; m++){
                                    var answer_row = $(widget.find('.widget-edit').find('.col-edit-row ul li').get(m)).find('input').val();
                                    arrAnswerRow.push(answer_row);
                                }
                                var arrAnswerColumn = Array();
                                for(var n = 0; n < column_size; n++){
                                    var answer_column = $(widget.find('.widget-edit').find('.col-edit-column ul li').get(n)).find('input').val();
                                    arrAnswerColumn.push(answer_column);
                                }
                                $.ajax({
                                    type:"POST",
                                    url:Root_url+"management/saveQuestionTable",
                                    dataType: "json",
                                    data:{'scid': scid, 'question_title': question_title, 'question_type': 3, 'answerRow': arrAnswerRow, 'answerColumn': arrAnswerColumn, 'position': i},
                                    success:(function(data){

                                    })
                                });

                                break;
                            }
                            default :{
                                break;
                            }
                        }
                    }
                    if(i == size){
                        location.href = Root_url + "management#survey/"+scid;
                    }
                }
            })
        });
    }
}

function updateSurvey(obj){
    var survey_child_title = $('#survey_title');
    if(survey_child_title.val() == ""){
        $('body').scrollTop(0);
        survey_child_title.effect('highlight', {color: 'rgb(255, 182, 193)'}, 500);
        survey_child_title.find('textarea').focus();
    }else{
        var sid = $('#survey_folder').val();
        var scid = $('.survey-page-content').attr('scid');
        var widget_box = $('.widget-box');
        var size = widget_box.size();
        //Từng câu hỏi
        for(var i = 0; i< size; i++){
            var widget = $(widget_box.get(i));
            var question_title = widget.find('.widget-header').find('.col-title').text();
            var question_type = widget.attr('builder');
            var qid = widget.attr('qid');
            var question_size = 0;
            if(qid){
                //update question
                switch(question_type){
                    case "1":{
                        question_size = widget.find('.widget-edit').find('.widget-edit-answer ul li').size();
                        var arrAnswer = Array();
                        for(var j = 0; j < question_size; j++){
                            var answer_text = $(widget.find('.widget-edit').find('.widget-edit-answer ul li').get(j)).find('input').val();
                            arrAnswer.push(answer_text);
                        }
                        $.ajax({
                            type:"POST",
                            url:Root_url+"management/updateQuestionSingle",
                            dataType: "json",
                            data:{'question_title': question_title, 'answer': arrAnswer, 'position': i},
                            success:(function(data){

                            })
                        });
                        break;
                    }
                    case "2":{
                        question_size = widget.find('.widget-edit').find('.widget-edit-answer ul li').size();
                        arrAnswer = Array();
                        for(var j = 0; j < question_size; j++){
                            answer_text = $(widget.find('.widget-edit').find('.widget-edit-answer ul li').get(j)).find('input').val();
                            arrAnswer.push(answer_text);
                        }
                        $.ajax({
                            type:"POST",
                            url:Root_url+"management/updateQuestionMultiple",
                            dataType: "json",
                            data:{'question_title': question_title, 'answer': arrAnswer, 'position': i},
                            success:(function(data){

                            })
                        });
                        break;
                    }
                    case "3":{
                        var row_size = widget.find('.widget-edit').find('.col-edit-row ul li').size();
                        var column_size = widget.find('.widget-edit').find('.col-edit-column ul li').size();
                        var arrAnswerRow = Array();
                        for(var m = 0; m < row_size; m++){
                            var answer_row = $(widget.find('.widget-edit').find('.col-edit-row ul li').get(m)).find('input').val();
                            arrAnswerRow.push(answer_row);
                        }
                        var arrAnswerColumn = Array();
                        for(var n = 0; n < column_size; n++){
                            var answer_column = $(widget.find('.widget-edit').find('.col-edit-column ul li').get(n)).find('input').val();
                            arrAnswerColumn.push(answer_column);
                        }
                        $.ajax({
                            type:"POST",
                            url:Root_url+"management/updateQuestionTable",
                            dataType: "json",
                            data:{'question_title': question_title, 'answerRow': arrAnswerRow, 'answerColumn': arrAnswerColumn, 'position': i},
                            success:(function(data){

                            })
                        });
                        break;
                    }
                    default: {
                        break;
                    }
                }

            }else{
                //add new question into survey
                switch(question_type){
                    case "1":{
                        question_size = widget.find('.widget-edit').find('.widget-edit-answer ul li').size();
                        arrAnswer = Array();
                        for(j = 0; j < question_size; j++){
                            answer_text = $(widget.find('.widget-edit').find('.widget-edit-answer ul li').get(j)).find('input').val();
                            arrAnswer.push(answer_text);
                        }
                        $.ajax({
                            type:"POST",
                            url:Root_url+"management/saveQuestionSingle",
                            dataType: "json",
                            data:{'scid': scid, 'question_title': question_title, 'question_type': 1, 'answer': arrAnswer, 'position': i},
                            success:(function(data){

                            })
                        });
                        break;
                    }
                    case "2":{
                        question_size = widget.find('.widget-edit').find('.widget-edit-answer ul li').size();
                        arrAnswer = Array();
                        for(var j = 0; j < question_size; j++){
                            answer_text = $(widget.find('.widget-edit').find('.widget-edit-answer ul li').get(j)).find('input').val();
                            arrAnswer.push(answer_text);
                        }
                        $.ajax({
                            type:"POST",
                            url:Root_url+"management/saveQuestionMultiple",
                            dataType: "json",
                            data:{'scid': scid, 'question_title': question_title, 'question_type': 2, 'answer': arrAnswer, 'position': i},
                            success:(function(data){

                            })
                        });
                        break;
                    }
                    case "3":{
                        row_size = widget.find('.widget-edit').find('.col-edit-row ul li').size();
                        column_size = widget.find('.widget-edit').find('.col-edit-column ul li').size();
                        arrAnswerRow = Array();
                        for(m = 0; m < row_size; m++){
                            answer_row = $(widget.find('.widget-edit').find('.col-edit-row ul li').get(m)).find('input').val();
                            arrAnswerRow.push(answer_row);
                        }
                        arrAnswerColumn = Array();
                        for(n = 0; n < column_size; n++){
                            answer_column = $(widget.find('.widget-edit').find('.col-edit-column ul li').get(n)).find('input').val();
                            arrAnswerColumn.push(answer_column);
                        }
                        $.ajax({
                            type:"POST",
                            url:Root_url+"management/saveQuestionTable",
                            dataType: "json",
                            data:{'scid': scid, 'question_title': question_title, 'question_type': 3, 'answerRow': arrAnswerRow, 'answerColumn': arrAnswerColumn, 'position': i},
                            success:(function(data){

                            })
                        });
                        break;
                    }
                    default: {
                        break;
                    }
                }
            }
        }
    }
}

function removeSurveyChild(obj){
    obj = $(obj);
    var scid = obj.attr('scid');
    $.ajax({
        type:"POST",
        url:Root_url+"management/removeSurveyChild",
        dataType: "json",
        data:{'scid': scid},
        success:(function(data){
            window.location.reload();
        })
    });
}

function editQuestion(obj){
    obj = $(obj);
    var widget_box = obj.parent().parent();
    widget_box.addClass('widget-editing');
    widget_box.find('.widget-question').hide();
    widget_box.find('.widget-edit').show();

}

function removeQuestion(obj){
    obj = $(obj);
    obj.parent().parent().remove();
    //update question number
    var widget = $('.widget-box');
    var size = widget.size();
    for(var i= 0; i < size; i++){
        $(widget.get(i)).find('.col-number').text(i+1);
    }
}

//get buzzer campaign
function getBuzzer(){
    var total = $('#total_criteria');
    var gender = total.find('.gender').val();
    var begin_age = total.find('.begin_age').val();
    var end_age = total.find('.end_age').val();
    var location = total.find('.location');
    var criteria = total.find('.criteria');

    var profile = total.find('.profile');
    var beautiful = total.find('.beautiful');
    var family = total.find('.family');
    var sport = total.find('.sport');
    var works = total.find('.works');
    var sales = total.find('.sales');
    var technology = total.find('.technology');
    var eatanddrink = total.find('.eatanddrink');
    var hobby = total.find('.hobby');

    //Location
    var province = new Array();
    location.each(function(){
        province.push($(this).val());
    });

    //profile
    var profileArr = new Array();
    //beautiful
    var beautifulArr = new Array();
    //family
    var familyArr = new Array();
    //sport
    var sportArr = new Array();
    //works
    var worksArr = new Array();
    //sales
    var salesArr = new Array();
    //technology
    var technologyArr = new Array();
    //eatanddrink
    var eatanddrinkArr = new Array();

    //hobby
    var hobbyArr = new Array();
    //Criteria
    criteria.each(function(){
        var cid = $(this).attr("cid");
        var value = $(this).val();
        var profile = "1";
        var beautiful = "2";
        var family = "3";
        var sport = "4";
        var works = "19";
        var sales = "20";
        var technology = "21";
        var eatanddrink = "22";
        var hobby = "23";
        switch (cid){
            case profile:{
                profileArr.push(value);
                break;
            }
            case beautiful:{
                break;
            }
            case family:{
                break;
            }
            case sport:{
                break;
            }
            case works:{
                break;
            }
            case sales:{
                break;
            }
            case technology:{
                break;
            }
            case eatanddrink:{
                break;
            }
            case hobby:{
                break;
            }
            default :{
                break;
            }
        }

    });





    //Criteria
    /*var tag = new Array();
    criteria.each(function(){
        tag.push($(this).val());
    });*/

    var result = $('.col-criteria-result');
    result.find('.research .people').hide();
    result.find('.research .loading').css('opacity', '1');

    //get Buzzer
    $.ajax({
        type:"POST",
        url:"management/getBuzzer",
        dataType: "json",
        data:{'gender': gender, 'begin': begin_age, 'end': end_age, 'location': province, 'profile': profileArr},
        success:(function(data){
            var number = data.data.length;

            result.find('.research .people').text(number + " people").show();
            result.find('.research .loading').css('opacity', '0');
        })
    });
}